﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using BLL = KC.Business.Web.MV8;
using DAL = KC.DataAccess.MV;

public partial class Post : System.Web.UI.Page
{
	public DAL.Post p;
	public DAL.MV8DataContext dc;
	protected void Page_Load(object sender, EventArgs e)
    {
		dc = new DAL.MV8DataContext(ConfigurationManager.ConnectionStrings["MV8"].ConnectionString);
		Dictionary<string, string> values;
		
		KC.Business.Web.MV8.DetectRequestType(Request.RawUrl, out values);
		if (!values.ContainsKey("id") && !values.ContainsKey("title")) Response.Redirect(".");
		int id;
		
		if (p == null) p = null; // trick IDE into thinking I've initialized my p

		if (values.ContainsKey("id") && int.TryParse(values["id"], out id)) {
			var posts = from p2 in dc.Posts where p2.ID == id select p2;
			if (posts.Count() == 0) Response.Redirect(".");
			p = posts.First(); }
		else if (values.ContainsKey("title") && !string.IsNullOrEmpty(values["title"])) {
			string title = Server.UrlEncode(values["title"]);
			var posts = from p2 in dc.Posts where p2.FriendlyName == title select p2;
			if (posts.Count() == 0) Response.Redirect(".");
			p = posts.First(); }
		else {
			//TODO
			//KC.Logging.Logger.Write("MV7", "User arrived at Post.aspx without a valid request", "No ID nor Title detected in URL "+Request.RawUrl, KC.Logging.Logger.Severity.Error);
			Response.Redirect("."); }

		//TODO
		//Master.LogActivity(p.ID);
		PopulatePost(p, dc);

		// Detect and add canonical link
		string linkrel = string.IsNullOrEmpty(p.FriendlyName)
			? "<link rel=\"canonical\" href=\"http://www.kconnolly.net/Post.aspx?ID=" + p.ID.ToString() + "\" />"
			: "<link rel=\"canonical\" href=\"http://www.kconnolly.net/Post.aspx?Title=" + p.FriendlyName + "\" />";
		Page.Header.Controls.Add(new LiteralControl(linkrel));

    }

	private void PopulatePost(DAL.Post p, DAL.MV8DataContext dc)
	{
		lblBody.Text = KC.Business.Text.Encoding.BlogDecodeForRendering(p.Body);
		lblCreated.Text = "Posted " + p.Created.ToString();
		hlTitle.Text = p.Title;
		hlTitle.NavigateUrl = string.IsNullOrEmpty(p.FriendlyName)
			? "Post.aspx?ID=" + p.ID.ToString()
			: "Post.aspx?Title=" + p.FriendlyName;
		this.Page.Title = "Kevin Connolly &gt; Blog &gt; " + p.Title;

		//lblIP.Text = Request.UserHostAddress.ToString();
		//rComments.DataSource = from c in dc.Comments where c.Activity.PID == p.ID && (c.isApproved || !c.isRequireMod) select c;
		//rComments.DataBind();
	}

	//protected void rComments_ItemDataBound(object sender, RepeaterItemEventArgs e)
	//{
	//    if (e == null || e.Item.DataItem == null) return;
	//    Comment c = (Comment)e.Item.DataItem;
	//    Label lbl = (Label)e.Item.FindControl("lblComment");
	//    lbl.Text = Server.HtmlEncode(c.Body);
	//    if (lbl.Text.Length > 1000) lbl.Text = lbl.Text.Substring(0, 995) + " [...]";


	//    Label lblDatetime = (Label)e.Item.FindControl("lblDatetime");
	//    lblDatetime.Text = c.DateTime.ToString("MM/dd/yyyy HH:mm:ss");
	//}


	//protected void btnSubmit_Click(object sender, EventArgs e)
	//{
	//    if (!reCaptcha.IsValid) {
	//        err("Enter CAPTCHA to continue");
	//        return; }
	//    if (Master.act.Session.IP.NumProblems > 0) {
	//        err("Problems have been recorded from your IP address. No can do.");
	//        return; }
	//    if (Master.act.Session.User != null && Master.act.Session.User.BanLevel > 0) {
	//        err("Problems have been recorded from the logged in user.  No can do.");
	//        return; }

	//    string text = txtComment.Text;
	//    foreach (BannedWord bw in dc.BannedWords)
	//        if (text.ToLower().Contains(bw.word.ToLower())) {
	//            text = text.ToLower().Replace(bw.word.ToLower(), "(Banned Word)");
	//            Master.act.Session.IP.NumProblems++;
	//            Master.act.Session.IP.Notes += "; used banned word \"" + bw.word + "\"";
	//            dc.SubmitChanges(); }


	//    // Comment is good enough for now. Post it, post it good.
	//    Comment comment = new Comment();
	//    comment.AID = Master.act.ID;
	//    comment.Body = text;
	//    comment.DateTime = DateTime.Now;
	//    comment.isRequireMod = true;
	//    dc.Comments.InsertOnSubmit(comment);

	//    Activity act = (from a in dc.Activities where a.ID == Master.act.ID select a).First();
	//    act.PID = p.ID;
	//    dc.SubmitChanges();
	//    PopulatePost(p, dc);

	//    // Notify me there has been a new comment posted
	//    for (int i = 0; i < 3; i++)
	//        Console.Beep(2000 + (i * 250), 500);

	//    err("Comment " + comment.ID.ToString() + " has been posted and is awaiting Moderation.");
	//	}
	//private void err(string msg)
	//{
	//    lblError.Visible = true;
	//    lblError.Text = msg;
	//}
}